<template>
  <div>
    <JSelectBiz @handleOpen="handleOpen" :loading="loadingEcho" v-bind="attrs" />
    <DataGroupListDrawer @register="regDrawer" @getSelectResult="setValue" v-bind="getBindValue" showFooter/>
  </div>
</template>
<script lang="ts">
import JSelectBiz from '/@/components/Form/src/jeecg/components/base/JSelectBiz.vue';
import {defineComponent, provide, reactive, ref, toRaw, unref, watch, watchEffect} from 'vue';

import {useDrawer} from '/@/components/Drawer';
import {propTypes} from '/@/utils/propTypes';
import {useRuleFormItem} from '/@/hooks/component/useFormItem';
import {useAttrs} from '/@/hooks/core/useAttrs';
import {SelectValue} from 'ant-design-vue/es/select';
import {listDataGroupTree} from '/@/api/infra/dataGroup'
import {createAsyncComponent} from '/@/utils/factory/createAsyncComponent';

export default defineComponent({
    name: 'MySelectDataGroup',
    components: {
      //此处需要异步加载
      DataGroupListDrawer : createAsyncComponent(() => import('./DataGroupListDrawer.vue'), {
        loading: true,
      }),
      JSelectBiz,
    },
    inheritAttrs: false,
    props: {
      value: propTypes.oneOfType([propTypes.string, propTypes.array]),
      // 是否允许多选，默认 false
      multiple: propTypes.bool.def(false),
      // 删除api
      deleteApi: { type: Function, default: () => {} },
      // 保存或者更新api
      saveOrUpdateApi: { type: Function, default: () => {} },
      // 批量删除api
      batchDeleteApi: { type: Function, default: () => {} },
      title: propTypes.string.def('数据分组'),
      bizType: propTypes.number.def(-1),
      // 最大选择的数
      maxSelectCount: propTypes.number.def(-1),
    },
    emits: ['options-change', 'change', 'select', 'update:value'],
    setup(props, { emit, refs }) {
      const emitData = ref<any[]>();
      //注册model
      const [regDrawer, { openDrawer }] = useDrawer();
      //表单值
      const [state] = useRuleFormItem(props, 'value', 'change', emitData);
      //下拉框选项值
      const selectOptions = ref<SelectValue>([]);
      //下拉框选中值
      let selectValues = reactive<any>({
        value: [], change: false
      });
      // 是否正在加载回显数据
      const loadingEcho = ref<boolean>(false);
      //下发 selectOptions,xxxBiz组件接收
      provide('selectOptions', selectOptions);
      //下发 selectValues,xxxBiz组件接收
      provide('selectValues', selectValues);
      //下发 loadingEcho,xxxBiz组件接收
      provide('loadingEcho', loadingEcho);

      const tag = ref(false);
      const init = ref(false);
      const attrs = useAttrs();

      /**
       * 监听组件值
       */
      watchEffect(() => {
        props.value && initValue();
      });

      // 为了解决弹窗form初始化赋值问题
      watch(
        () => props.value,
        () => {
          initValue();
        }
      );

      /**
       * 监听selectValues变化
       */
      watch(selectValues, () => {
        if (selectValues) {
          state.value = selectValues.value;
        }
      });
      /**
       * 监听selectOptions变化
       */
      watch(selectOptions, () => {  
        if (selectOptions) {
          emit('select', toRaw(unref(selectOptions)), toRaw(unref(selectValues)));
        }
      });

      /**
       * 打卡弹出框
       */
      function handleOpen() {
        tag.value = true;
        const getBindValue = Object.assign({...props}, unref(attrs));
        openDrawer(true, {
          isUpdate: false, ...getBindValue, api: listDataGroupTree
        });
      }

      /**
       * 将字符串值转化为数组
       */
      function initValue() {
        let value = props.value ? props.value : [];
        if (value && typeof value === 'string') {
          state.value = value.split(',');
          selectValues.value = value.split(',');
        } else {
          // 兼容数组（行编辑的用法问题）
          selectValues.value = value;
        }
      }

      /**
       * 设置下拉框的值
       */
      function setValue(options, values) {
        selectOptions.value = options;
        //emitData.value = values.join(",");
        state.value = values;
        selectValues.change = true
        selectValues.value = values;
        
        emit('update:value', values.join(','));
        emit('change', values.join(','));
      }
      const getBindValue = Object.assign({}, unref(props), unref(attrs));
      return {
        state,
        attrs,
        selectOptions,
        selectValues,
        loadingEcho,
        getBindValue,
        tag,
        regDrawer,
        setValue,
        handleOpen,
      };
    },
  });
</script>
<style lang="less" scoped>
  .j-select-row {
    @width: 82px;

    .left {
      width: calc(100% - @width - 8px);
    }

    .right {
      width: @width;
    }

    .full {
      width: 100%;
    }

    :deep(.ant-select-search__field) {
      display: none !important;
    }
  }
</style>
